<?php

namespace api\agent;

use model\repo\DropCatch;

class Collector
{
    /** @var GName */
    private $gname;
    /** @var string */
    private $lock;

    public function __construct(/* string */ $appId, /* string */ $appKey)
    {
        $this->gname = new GName($appId, $appKey);
        $this->lock = PROJECT_DIR."/data/first_run.lock";
    }

    public function hasRunEver() {
        if (file_exists($this->lock)) {
            return true;
        }
        $lockFile = fopen($this->lock, "w");
        $content = sprintf("%d", time());
        fwrite($lockFile, $content, strlen($content));
        fclose($lockFile);
        return false;
    }

    public function run(/* string */ $sDate, /* int */ $page, /* int */ $size = 1000)
    {
        $domains = $this->gname->dropCatch($sDate, $page, $size);
        if (empty($domains)) {
            printf("END\n");
            return 0;
        }
        $dc = new DropCatch();
        foreach ($domains as $d) {
            $d['updated_at'] = date("Y-m-d H:i:s", time());

            $thisDomain = $dc->findByDomain($d['domain']);
            if (!empty($thisDomain)) {
                // $dc->writeLog($d['domain']);
                $dupId = $thisDomain['_id'];
                $dc->updateDomain($d, $dupId);
                continue;
            }
            $d['created_at'] = date("Y-m-d H:i:s", time());
            $dc->create($d);
        }
        return count($domains);
    }

}